﻿/*
Configuration Server
 
Provides a single configuration point for the several instances (development, 
staging, testing, production, etc.) for web sites
 
Includes ideas and code from all over the internet. Specially, stacktrace, msdn, github.
 
Copyright (C) 2014 by Jaime Espinosa <jaimeespinosa60@gmail.com>
 
The MIT License (MIT)

Copyright (c) 2014 jaime espinosa

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

  @author Jaime Espinosa <jaimeespinosa60@gmail.com>
  @package configuracion
  @version 0.1
*/

using Configuracion.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Web.Mvc;

namespace Configuracion.Controllers
{
    public class BundleController : baseController
    {
        [Authorize]
        public ActionResult list(int ownerId = 0)
        {
            ViewBag.Exception = "";
            string strUserName = "";

            IQueryable<mdlOwner> ownerList = default(IQueryable<mdlOwner>);

            if (User.Identity.IsAuthenticated)
                strUserName = User.Identity.Name;

            if (ownerId == 0)
                ownerList = from p in dbContext.Owners.Include(p => p.bundles)
                            where p.users.Any(u => u.userName == strUserName)
                            select p;
            else
                ownerList = from p in dbContext.Owners.Include(p => p.bundles)
                            where p.users.Any(u => u.userName == strUserName)
                                      & p.ID == ownerId
                            select p;

            if ((ownerList == null) || (ownerList.Count() < 1))
                return RedirectToAction("list", "owner");

            return View(ownerList);
        }
        [Authorize]
        public JsonResult newBundle(int ownerId = 0, string strName = "", string strDescription = "", string strUrl = "")
        {
            string strError = "";
            string strUserName = "";
            mdlBundle newBundle = default(mdlBundle);

            if ((ownerId == 0) || (strName == "") || (strDescription == ""))
            {
                return Json(new { error = "invalid parameters" }, JsonRequestBehavior.AllowGet);
            }

            try
            {
                if (User.Identity.IsAuthenticated)
                    strUserName = User.Identity.Name;

                mdlOwner owner = (from p in dbContext.Owners.Include(p => p.bundles)
                                  where p.users.Any(u => u.userName == strUserName)
                                     & p.ID == ownerId
                                  select p).FirstOrDefault<mdlOwner>();

                newBundle = new mdlBundle();
                newBundle.name = strName;
                newBundle.description = strDescription;
                newBundle.url = strUrl;


                owner.bundles.Add(newBundle);

                dbContext.Bundles.Add(newBundle);

                if (dbContext.GetValidationErrors().Count() > 0)
                {
                    foreach (System.Data.Entity.Validation.DbEntityValidationResult error in dbContext.GetValidationErrors())
                        foreach (System.Data.Entity.Validation.DbValidationError valerror in error.ValidationErrors)
                            strError += valerror.ErrorMessage.ToString() + "<br/>";

                    return Json(new { error = "Please verify:" + strError.ToString() }, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    dbContext.SaveChanges();
                    return Json(new { OK = "Bundle created" }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                return Json(new { error = infoExcepcion(ex) }, JsonRequestBehavior.AllowGet);
            }
        }
        [Authorize]
        public JsonResult editBundle(int bundleID = 0, string strName = "", string strDescription = "", string strUrl = "")
        {
            string strError = "";
            string strUserName = "";
            mdlBundle editBundle = default(mdlBundle);

            if ((bundleID == 0) || (strName == "") || (strDescription == ""))
            {
                return Json(new { error = "invalid parameters" }, JsonRequestBehavior.AllowGet);
            }

            try
            {
                if (User.Identity.IsAuthenticated)
                    strUserName = User.Identity.Name;

                editBundle = (from p in dbContext.Owners
                                   .Where(p => p.users.Any(u => u.userName == strUserName))
                                   .SelectMany(p => p.bundles)
                              where p.ID == bundleID
                              select p).FirstOrDefault<mdlBundle>();

                if (editBundle == null)
                    return Json(new { error = "Bundle not found" }, JsonRequestBehavior.AllowGet);

                // UPDATES Bundle
                editBundle.name = strName;
                editBundle.description = strDescription;
                editBundle.url = strUrl;

                if (dbContext.GetValidationErrors().Count() > 0)
                {
                    foreach (System.Data.Entity.Validation.DbEntityValidationResult error in dbContext.GetValidationErrors())
                        foreach (System.Data.Entity.Validation.DbValidationError valerror in error.ValidationErrors)
                            strError += valerror.ErrorMessage.ToString() + "<br/>";

                    return Json(new { error = "Please verify:" + strError.ToString() }, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    dbContext.SaveChanges();
                    return Json(new { OK = "Bundle updated" }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                return Json(new { error = infoExcepcion(ex) }, JsonRequestBehavior.AllowGet);
            }
        }
        [Authorize]
        public JsonResult dropBundle(int bundleID = 0)
        {
            string strError = "";
            string strUserName = "";
            mdlBundle removeBundle = default(mdlBundle);

            if (bundleID == 0)
            {
                return Json(new { error = "invalid parameters" }, JsonRequestBehavior.AllowGet);
            }

            try
            {
                if (User.Identity.IsAuthenticated)
                    strUserName = User.Identity.Name;

                removeBundle = (from p in dbContext.Owners
                                     .Where(p => p.users.Any(u => u.userName == strUserName))
                                     .SelectMany(p => p.bundles)
                                where p.ID == bundleID
                                select p).FirstOrDefault<mdlBundle>();

                if (removeBundle == null)
                    return Json(new { error = "Bundle not found" }, JsonRequestBehavior.AllowGet);

                // REMOVE THE Bundle
                dbContext.Bundles.Remove(removeBundle);

                if (dbContext.GetValidationErrors().Count() > 0)
                {
                    foreach (System.Data.Entity.Validation.DbEntityValidationResult error in dbContext.GetValidationErrors())
                        foreach (System.Data.Entity.Validation.DbValidationError valerror in error.ValidationErrors)
                            strError += valerror.ErrorMessage.ToString() + "<br/>";

                    return Json(new { error = "Please verify:" + strError.ToString() }, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    dbContext.SaveChanges();
                    return Json(new { OK = "Bundle removed" }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                return Json(new { error = infoExcepcion(ex) }, JsonRequestBehavior.AllowGet);
            }
        }
        [Authorize]
        public JsonResult infoBundle(int bundleID = 0)
        {
            string strUserName = "";
            mdlBundle returnBundle = default(mdlBundle);

            if (bundleID == 0)
            {
                return Json(new { error = "invalid parameters" }, JsonRequestBehavior.AllowGet);
            }

            try
            {
                if (User.Identity.IsAuthenticated)
                    strUserName = User.Identity.Name;

                returnBundle = (from p in dbContext.Owners
                                .Where(p => p.users.Any(u => u.userName == strUserName))
                                .SelectMany(p => p.bundles)
                                where p.ID == bundleID
                                select p).FirstOrDefault<mdlBundle>();

                if (returnBundle == null)
                    return Json(new { error = "Bundle not found" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { error = infoExcepcion(ex) }, JsonRequestBehavior.AllowGet);
            }

            return Json(new { OK = "Bundle obtained", data = returnBundle }, JsonRequestBehavior.AllowGet);
        }
        [Authorize]
        public JsonResult bundleList(int ownerId = 0)
        {
            string strUserName = "";
            IQueryable<mdlBundle> lstBundles = default(IQueryable<mdlBundle>);

            if (ownerId == 0)
            {
                return Json(new { error = "invalid parameters" }, JsonRequestBehavior.AllowGet);
            }

            try
            {
                if (User.Identity.IsAuthenticated)
                    strUserName = User.Identity.Name;

                lstBundles = (from p in dbContext.Owners
                               .Where(p => p.users.Any(u => u.userName == strUserName)
                               & p.ID == ownerId)
                               .SelectMany(p => p.bundles)
                              select p);
            }
            catch (Exception ex)
            {
                return Json(new { error = infoExcepcion(ex) }, JsonRequestBehavior.AllowGet);
            }

            return Json(new { OK = "List obtained", data = lstBundles }, JsonRequestBehavior.AllowGet);
        }
    }
}